package com.uinnova.product.eam.workable.rsm;

import com.obs.services.ObsClient;
import com.obs.services.model.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * 华为obs 官方sdk 资源操作工具类
 */
@Slf4j
public class HuaWeiObsRsmBehavior extends RsmOperationInfo implements RsmBehavior {


    private static ObsClient obsClient;

    public HuaWeiObsRsmBehavior(){
        super();
    }

    public HuaWeiObsRsmBehavior(String endPoint, String accessKey, String secretKey,
                                String bucketName, Long urlExpireSeconds){
        super();
        this.endpoint = endPoint;
        this.accessKey = accessKey;
        this.secretKey = secretKey;
        this.bucketName = bucketName;
        this.urlExpireSeconds = urlExpireSeconds;

        initClient();

    }

    /**
     * 初始化client方法
     */
    @Override
    public void initClient() {
        if(this.obsClient == null){
            String endpoint = "https://" + this.endpoint;
            this.obsClient = new ObsClient(this.accessKey,secretKey,endpoint);
        }
    }

    /**
     * 关闭Client方法
     */
    @Override
    public void closeClient() {
        if(obsClient != null){
            try {
                obsClient.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 上传资源文件-通过本地文件进行上传
     *
     * @param objectKey
     * @param file
     * @return
     */
    @Override
    public boolean uploadRsm(String objectKey, File file) {

        int s = objectKey.lastIndexOf("/");
        String fileName = "";
        if(s>=0){
            fileName = objectKey.substring(s+1);
        }else {
            fileName = objectKey;
        }
        log.info("进入华为 SDK上传资源：" + fileName);

        PutObjectRequest request = new PutObjectRequest();
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentType("application/octet-stream");
        objectMetadata.setContentDisposition("attachment;filename=" + fileName);
        request.setBucketName(this.bucketName);
        request.setObjectKey(objectKey);
        request.setMetadata(objectMetadata);
        request.setFile(file);

        PutObjectResult uploadResult = obsClient.putObject(request);

        //如果上传失败，等待100ms后再重试一次
        if(uploadResult != null && uploadResult.getStatusCode() != 200){
            try {
                Thread.sleep(100);
                obsClient.putObject(request);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

        return true;
    }


    /**
     * 下载资源
     *
     * @param objectKey
     * @return
     */
    @Override
    public InputStream downloadRsm(String objectKey) {
        ObsObject obsObject = obsClient.getObject(this.bucketName, objectKey);
        if(obsObject != null){
            return obsObject.getObjectContent();
        }else {
            return null;
        }
    }

    /**
     * 获得资源的临时访问链接
     *
     * @param objectKey
     * @return
     */
    @Override
    public String getRsmUrlWithAccess(String objectKey) {

        TemporarySignatureRequest temporarySignatureRequest =
                new TemporarySignatureRequest(HttpMethodEnum.GET, urlExpireSeconds);
        temporarySignatureRequest.setBucketName(this.bucketName);
        temporarySignatureRequest.setObjectKey(objectKey);

        TemporarySignatureResponse temporarySignatureResponse =
                obsClient.createTemporarySignature(temporarySignatureRequest);

        return temporarySignatureResponse.getSignedUrl();
    }

    /**
     * 删除资源
     * @param objectKey
     * @return
     */
    @Override
    public boolean deleteRsm(String objectKey) {
        if(StringUtils.isNotBlank(objectKey)){
            if(obsClient.doesObjectExist(this.bucketName, objectKey)){

                DeleteObjectRequest deleteObjectRequest = new DeleteObjectRequest();
                deleteObjectRequest.setBucketName(this.bucketName);
                deleteObjectRequest.setObjectKey(objectKey);

                obsClient.deleteObject(deleteObjectRequest);

                return true;
            }
        }
        return false;
    }
}
